package com.example.demo.rocketmq;


import com.example.demo.dao.bonus.BonusEventLogMapper;
import com.example.demo.dao.user.UserMapper;
import com.example.demo.domain.dto.messaging.UserAddBonusMsgDTO;
import com.example.demo.domain.entity.bonus.BonusEventLog;
import com.example.demo.domain.entity.user.User;
import com.example.demo.service.user.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
@RocketMQMessageListener(consumerGroup = "consumer-group", topic = "add-bonus")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AddBonusListener implements RocketMQListener<UserAddBonusMsgDTO> {
    private final UserMapper userMapper;
    private final BonusEventLogMapper bonusEventLogMapper;


    @Override
    public void onMessage(UserAddBonusMsgDTO userAddBonusMsgDTO) {
        Integer userId = userAddBonusMsgDTO.getUserId();
        Integer bonus = userAddBonusMsgDTO.getBonus();
        User user = this.userMapper.selectByPrimaryKey(userId);
        user.setBonus(user.getBonus() + bonus);
        this.userMapper.updateByPrimaryKeySelective(user);

        this.bonusEventLogMapper.insert(
                BonusEventLog.builder().userId(userId).value(bonus).event("投稿")
                        .createTime(new Date()).description("投稿加积分").build());
    }
}
